package com.w4cms.controller.admin;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.w4cms.core.Consts;
import com.w4cms.interceptor.AdminInterceptor;
import com.w4cms.model.Category;
import com.w4cms.model.SysUser;
import com.w4cms.model.TreeData;
import com.w4cms.utils.Tools;
@ControllerBind(controllerKey="/admin/category",viewPath="admin/category")
@Before(AdminInterceptor.class)
public class CategoryController extends Controller {
	
	public void list(){
		this.search();
	}
	public void add(){
		Category m = Category.dao.findFirst("select max(cate_order) as maxOrder from category");
		List<TreeData> list = Category.dao.cateTree(null);
		setAttr("list", list);
		setAttr("order", m.getInt("maxOrder")!=null?m.getInt("maxOrder")+1:0);
		render("categoryinfo.html");
	}
	public void edit(){
		Object id = getPara();
		List<TreeData> list = Category.dao.cateTree(null);
		setAttr("list", list);
		Category m = Category.dao.findById(id);
		setAttr("obj", m);
		render("categoryinfo.html");
	}
	public void save(){
		String id = getPara("id");
		boolean isOk = false;
		SysUser u = (SysUser) getSession().getAttribute(Consts.SESSION_USER);
		if(Tools.isEmpty(id)){
			isOk = new Category().set("id", UUID.randomUUID().toString()).set("name", getPara("name")).set("parent_id", getPara("pid")).set("cate_order", getPara("order")).set("remark", getPara("remark"))
					.set("status", getPara("status")).set("user_id", u.getInt("id")).set("create_time", new Date()).set("update_time", new Date()).save();
		}else{
			isOk = new Category().set("id", id).set("name", getPara("name")).set("parent_id", getPara("pid")).set("cate_order", getPara("order")).set("remark", getPara("remark"))
					.set("status", getPara("status")).set("update_time", new Date()).update();
		}
		if(isOk){
			renderJson("success",true);
		}else{
			renderJson("msg","操作失败.");
		}
	}
	
	public void delete(){
		Object id= getPara();
		boolean isOk = Category.dao.deleteById(id);
		if(isOk){
			renderText("true");
		}else{
			renderText("删除分类失败.");
		}
	}
	
	public void disable(){
		Object id= getPara();
		boolean isOk = new Category().set("id", id).set("status", 1).set("update_time", new Date()).update();
		if(isOk){
			renderText("true");
		}else{
			renderText("停用分类失败.");
		}
	}
	public void enable(){
		Object id= getPara();
		boolean isOk = new Category().set("id", id).set("status", 0).set("update_time", new Date()).update();
		if(isOk){
			renderText("true");
		}else{
			renderText("启用分类失败.");
		}
	}
	public void search(){
		String search = getPara("search");
		List<TreeData> list = Category.dao.searchCategoryTree(search);
		setAttr("list", list);
		keepPara();
		render("categorylist.html");
	}
}
